// This is the main DLL file.

#include "stdafx.h"
#include "CudaManager.h"
#include "InternalManager.h"
#include "CudaHostBuffer.h"
#include "CudaDeviceBuffer.h"
using namespace System::Runtime::InteropServices;

namespace GRIP
{
	namespace Cuda
	{
		void CudaManager::InitializeCuda()
		{
			InternalManager::Init();
		};

		void CudaManager::Cleanup()
		{
			InternalManager::Cleanup();
		};

		generic<typename T>
		void CudaManager::CopyBytesToDevice(array<T>^ Source, CudaDeviceBuffer^ Target)
		{
			GCHandle handle = GCHandle::Alloc(Source, GCHandleType::Pinned);
			CudaErrorCheck(cudaMemcpy(
				Target->Ptr(),
				(void*)handle.AddrOfPinnedObject(),
				Source->Length * sizeof(T),
				cudaMemcpyHostToDevice));
		};

		generic<typename T>
		void CudaManager::CopyBytesFromDevice(CudaDeviceBuffer^ Source, array<T>^ Target)
		{
			GCHandle handle = GCHandle::Alloc(Target, GCHandleType::Pinned);
			CudaErrorCheck(cudaMemcpy(
				(void*)handle.AddrOfPinnedObject(),
				Source->Ptr(),
				Target->Length * sizeof(T),
				cudaMemcpyDeviceToHost));
		};

		void CudaManager::RenderToMappedSource(CudaDeviceBuffer^ Source, CudaSource^ Target)
		{
			CudaErrorCheck(cudaMemcpyToArray(Target->GetMappedArray(), 0, 0, Source->Ptr(), Source->BufferSize(), cudaMemcpyDeviceToDevice));
		};

		int CudaManager::GetDevID()
		{
			return InternalManager::GetDevID();
		}
	}
}
